iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 22
0
Mobile Development

顏色 countenance APP製作筆記系列 第 22

[Day 22] 用FSCalendar製作月曆

  • 分享至 

  • xImage
  •  

有沒有需要在app中加入月曆的情況呢?這時是不是會覺得不知如何是好,別擔心!我找到了超好用的方法今天就分享給你知道~那就是「FSCalendar」有了他就可以快速產生月曆,還能夠使用各種擴充功能讓你的月曆更完整喔。

首先,你匯入需要的函式庫了嗎?

還沒的話趕快去看Firebase加入專案(下)

加入月曆

在Storyboard加入一個View,class輸入FSCalendar
https://ithelp.ithome.com.tw/upload/images/20200917/20130458vj9m3l9mu5.png
View Controller要繼承FSCalendarDelegate, FSCalendarDataSource以及import FSCalendar

Firebase部分請至Firebase系列文章查詢,此處只針對介面做說明

(範例檔:CalendarViewController.swift)

import UIKit
import FSCalendar
import FirebaseAuth
import FirebaseFirestore
import Firebase
import CoreData

class CalendarViewController: UIViewController,FSCalendarDelegate, FSCalendarDataSource {
    
    let db = Firestore.firestore()
    let userID = Auth.auth().currentUser!.uid
    var dateString = ""
    //紀錄有事件的日期,依據事件數量分為兩個
    var datesWithEvent = [String]()//小於等於3件事
    var datesWithMultipleEvents = [String]()//大於3件事
    //連結到Storyboard剛剛新增的FSCalendar
    @IBOutlet var calendar: FSCalendar!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        loadDateEvent()
        calendar.delegate = self
        calendar.dataSource = self
        calendar.appearance.headerTitleColor = UIColor(hexString: "#3D538B")
        calendar.today = nil
        calendar.appearance.selectionColor = UIColor(hexString: "#6687AD")
        calendar.appearance.weekdayTextColor = UIColor(hexString: "#3D538B")
    }
    
    override func viewWillAppear(_ animated: Bool) {
        loadDateEvent()
        //重載calendar.資料
        calendar.reloadData()
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        datesWithEvent = []
        datesWithMultipleEvents = []
    }
 
    //設定日期格式
    fileprivate lazy var dateFormatter2: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        return formatter
    }()    
    func loadDateEvent(){
        
        let context = CoreDataManager.shared.persistentContainer.viewContext

        let fetchRequest = NSFetchRequest<User>(entityName: "User")
        fetchRequest.fetchLimit = 1
        fetchRequest.predicate = NSPredicate(format: "firestoreID == %@", userID)

        do{
            let Userexist = try context.fetch(fetchRequest)

            let fetchRequest2 = NSFetchRequest<DateInfo>(entityName: "DateInfo")
            fetchRequest2.predicate = NSPredicate(format: "uuid == %@", Userexist[0].uuid! as CVarArg)

            do{
                let dateInfoexist = try context.fetch(fetchRequest2)
                
                for i in dateInfoexist{
                    var dateRemoveWeekofMonth = i.date!.dropLast()
                    dateRemoveWeekofMonth = dateRemoveWeekofMonth.dropLast()
                    
                    if(6-Int(i.eventCount) != 0 && 6-Int(i.eventCount) < 4){
                        datesWithEvent.append(String(dateRemoveWeekofMonth))
                    }else if ((6-Int(i.eventCount) > 3)){
                        datesWithMultipleEvents.append(String(dateRemoveWeekofMonth))
                    }

                }

            }catch let fetchError{
                print("Failed to fetch compaies: \(fetchError)")
            }
        }catch let fetchError{
            print("Failed to fetch User: \(fetchError)")
        }
    }
}

點擊日期後切換頁面

//點擊事件時
    func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) {

        //跳出當天紀錄
        dateString = self.dateFormatter2.string(from: date)

        
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        if let secondVC = storyboard.instantiateViewController(identifier: Constants.Storyboard.eventViewController) as? EventViewController{
            
            let backBarButtonItem = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil)
            navigationItem.backBarButtonItem = backBarButtonItem
 
            secondVC.dateS = dateString

            show(secondVC, sender: self)
        }
    }

月曆下方事件圖設定

    //事件圖片設定
    func calendar(_ calendar: FSCalendar, imageFor date: Date) -> UIImage? {

        let dateString = self.dateFormatter2.string(from: date)
		//小於等於3件事要顯示的圖片
        if self.datesWithEvent.contains(dateString) {
            return UIImage(named: "圖片名稱")!.resized(to: CGSize(width: 35, height: 35))
        }
//大於3件事要顯示的圖片
        if self.datesWithMultipleEvents.contains(dateString) {
            return UIImage(named: "圖片名稱")!.resized(to: CGSize(width: 35, height: 35))
        }

        return nil
    }

變更圖片尺寸

參考出處:https://stackoverflow.com/questions/2658738/the-simplest-way-to-resize-an-uiimage

extension UIImage {
    func resized(to size: CGSize) -> UIImage {
        return UIGraphicsImageRenderer(size: size).image { _ in
            draw(in: CGRect(origin: .zero, size: size))
        }
    }
}

成品

https://ithelp.ithome.com.tw/upload/images/20200917/20130458OsG8jZJ7zK.png

結語

有了FSCalendar真的對開發有了大大的幫助,除了上面有介紹到的部分還有很多功能等大家去發掘唷!除了程式可以對月曆做設定,也能在Storyboard直接設定唷~

參考出處:https://github.com/WenchaoD/FSCalendar
參考出處:https://juejin.im/post/6844903933840736263


上一篇
[Day 21] 水晶圖片上色 (漸層、單色)
下一篇
[Day 23] 用Charts製作圖表
系列文
顏色 countenance APP製作筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言